package com.fighYo.edu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fighYo.edu.entity.EduSubject;
import com.fighYo.edu.entity.SubjectData;
import com.fighYo.edu.entity.vo.SubjectNestedVo;
import com.fighYo.edu.entity.vo.SubjectVo;
import com.fighYo.edu.listen.EduSubjectListener;
import com.fighYo.edu.mapper.EduSubjectMapper;
import com.fighYo.edu.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author fighYo
 * @since 2021-08-23
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void saveSubject(MultipartFile file) {
        try {
            InputStream inputStream = file.getInputStream();
            EasyExcel.read(inputStream, SubjectData.class, new EduSubjectListener(this)).sheet().doRead();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<SubjectNestedVo> nestedList() {
        QueryWrapper<EduSubject> oneWrapper = new QueryWrapper<>();
        oneWrapper.eq("parent_id", "0");
        List<EduSubject> eduSubjects1 = baseMapper.selectList(oneWrapper);
        List<SubjectNestedVo> nestedVos = new ArrayList<>();
        for(EduSubject eduSubject1: eduSubjects1) {
            SubjectNestedVo nestedVo = new SubjectNestedVo();
            nestedVo.setTitle(eduSubject1.getTitle());
            nestedVo.setId(eduSubject1.getId());
            QueryWrapper<EduSubject> twoWrapper = new QueryWrapper<>();
            twoWrapper.eq("parent_id", nestedVo.getId());
            twoWrapper.orderByAsc("sort", "id");
            List<EduSubject> eduSubjects2 = baseMapper.selectList(twoWrapper);
            for(EduSubject eduSubject2: eduSubjects2) {
                nestedVo.getChildren().add(new SubjectVo(eduSubject2.getId(), eduSubject2.getTitle()));
            }
            nestedVos.add(nestedVo);
        }
        return nestedVos;
    }
}
